﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace SceneLib
{
    public class SceneModel : SceneObject
    {
        public string FileName { get; set; }
        public List<SceneTriangle> Triangles { get; set; }
        int intersectedTriangle;
       
        public int NumTriangles { get { return Triangles == null ? 0 : Triangles.Count; } }

        public SceneModel(string name, string filename)
        {
            Name = name;
            Triangles = new List<SceneTriangle>();
            FileName = filename;
            intersectedTriangle = 0;
        }

        public SceneTriangle GetTriangle(int index)
        {
            return Triangles == null || index < 0 || index > Triangles.Count ? null : Triangles[index];
        }

        public override Intersection Intersect(Vector e, Vector d, float t0, float tf, float time0, float timef)
        {
            Intersection iMin = Intersection.NOINTERSECT;
            intersectedTriangle = -1;

            for(int i = 0; i < Triangles.Count; i++)
            {
                SceneTriangle aObject = Triangles[i];
                List<Vector> vertexAux = new List<Vector>(aObject.Vertex);
                List<Vector> normalAux = new List<Vector>(aObject.Normal);

                for (int j = 0; j < aObject.Vertex.Count; j++)
                {
                    aObject.Vertex[j] = aObject.Vertex[j].Rotate(Rotation).Scale(Scale).Translate(Position);
                    aObject.Normal[j] = aObject.Normal[j].Rotate(Rotation);
                }

                Intersection intersection = aObject.Intersect(e, d, t0, tf, time0, timef);

                if (intersection.T < iMin.T)
                {
                    iMin = intersection;
                    intersectedTriangle = i;
                }
                aObject.Vertex = vertexAux;
                aObject.Normal = normalAux;
            }

            return iMin;
        }

        public override Vector GetTextureColor(Vector p)
        {
            SceneTriangle triangle = GetTriangle(intersectedTriangle);
            
            if (triangle != null)
            {
                List<Vector> vertexAux = new List<Vector>(triangle.Vertex);
                List<Vector> normalAux = new List<Vector>(triangle.Normal);

                for (int j = 0; j < triangle.Vertex.Count; j++)
                {
                    triangle.Vertex[j] = triangle.Vertex[j].Rotate(Rotation).Scale(Scale).Translate(Position);
                    triangle.Normal[j] = triangle.Normal[j].Rotate(Rotation); ;
                }
                
                Vector color = triangle.GetTextureColor(p);
                
                triangle.Vertex = vertexAux;
                triangle.Normal = normalAux;
                return color;
            }
            else
                return new Vector(1, 1, 1);
        }
    }
}
